package com.xunyji.demo03.realm.usedemo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author AltEnter
 * @create 2019-01-17 22:07
 * @desc IniRealm测试类
 **/
public class IniRealmDemo {

    @Test
    public void iniRealmTest() {
        //        01 创建Realm
        IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
//        02 创建SecurityManager并将Realm设置到SecurityManager中
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(iniRealm);

//        03 将SecurityManager设置到SecurityUtils中
        SecurityUtils.setSecurityManager(defaultSecurityManager);
//        04 从SecurityUtils中获取Subject
        Subject subject = SecurityUtils.getSubject();
//        05 将用户名和用户密码封装成一个Token
        UsernamePasswordToken token = new UsernamePasswordToken("zeus", "222222");
//        06 通过Subject进行登录认证
        try {
            subject.login(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        07 通过Subject判断登录认证结果
        System.out.println(String.format("认证结果为：%s", subject.isAuthenticated()));

        ArrayList<String> roleList = new ArrayList<String>();
        roleList.add("role1");
        System.out.println("是否有role1角色：" + Arrays.toString(subject.hasRoles(roleList)));
        System.out.println("是否有role1角色：" + subject.hasRole("role1"));
        subject.checkPermission("user:create");
    }

}

